package concurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

class Restaurant implements Runnable {
    private ExecutorService mExec;

    private List<WaitPerson> mWaitPersons = new ArrayList<WaitPerson>();

    private List<Chef> mChefs = new ArrayList<Chef>();

    private static Random sRand = new Random(47);

    /* package */ BlockingQueue<Order> mOrders = new LinkedBlockingQueue<Order>();

    public Restaurant(ExecutorService e, int waitPersons, int chefs) {
        mExec = e;
        for (int i = 0; i < waitPersons; i++) {
            WaitPerson waitPerson = new WaitPerson(this);
            mWaitPersons.add(waitPerson);
            mExec.execute(waitPerson);
        }
        for (int i = 0; i < chefs; i++) {
            Chef chef = new Chef(this);
            mChefs.add(chef);
            mExec.execute(chef);
        }
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                WaitPerson wp = mWaitPersons.get(sRand.nextInt(mWaitPersons.size()));
                Customer c = new Customer(wp);
                mExec.execute(c);
                TimeUnit.MILLISECONDS.sleep(100);
            }
        } catch (InterruptedException e) {
            System.out.println("Restaurant interrupted");
            // e.printStackTrace();
        }
        System.out.println("Restaurant closing");
    }
}
